﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Ordinapoche.Core
{
    public class Assembler
    {
        private List<AssemblerInstruction> _Instructions = new List<AssemblerInstruction> ();
        private Dictionary<string, int> _Symbols = new Dictionary<string, int> ();
        
        public AssemblerInstruction Parse (string aLine)
        {
            return null;
        }

        public void AddSource (IEnumerable<string> aSource)
        {
            foreach (var s in aSource)
            {
                _Instructions.Add (Parse (s));
            }
        }

        public void ResolveSymbols ()
        {
            bool complete = false;
            bool last = false;

            while (!complete)
            {
                int n = _Symbols.Count;
                int? location = 0;

                complete = true;

                foreach (var i in _Instructions)
                {
                    if (!i.ResolveSymbolsPass (ref location, _Symbols, last))
                    {
                        complete = false;
                        if (last)
                        {
                            throw new Exception ("Bardaf");
                        }
                    }
                }

                if (!complete && _Symbols.Count == n)
                {
                    //  Still not complete, but no symbol was added.
                    //  Give a last chance (that will fail) so that a proper error
                    //  message can be generated
                    last = true;
                }
            }
        }
    }
}
